(function ($) {

// Напоминание о выборе строки
	function selRowPlease() {
		app.alert('AlertDlg', 'Внимание', "Пожалуйста, выберите строку в таблице.", 'app-icon-stop32');
	}
	
	function selOnePlease() {
		app.alert('AlertDlg', 'Внимание', "Пожалуйста, выберите только одну строку в таблице.", 'app-icon-stop32');
	}
	
    function Jobs(area_id, caller) {
        var vdiv = area_id+'Tab';
		var area = $('#'+area_id);

		area.html('<div id="'+vdiv+'Pager"></div><table id="'+vdiv+'"></table>');
        
		var pager_id = '#' + vdiv + 'Pager';
        var pager = $(pager_id);
		
		var el_status;
		var el_start;
		var el_finish;
		
        var el_build_id;
        var el_build_name;
        var build_name = '';
		
        var el_cli_id;
        var el_cli_name;
		var cli_name;
		
        var el_jtp_id;
        var el_jtp_descr;
		var jtp_descr;
		
		var edit_div = 'div#editmod' + vdiv;

        var gritab;
        var col_order = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ];
        var col_names = ['Статис', 'ID', 'Начало', 'Стоимость', 'ID Объекта', 'Объект', 
						'ID заказчика', 'Заказчик', 'ID типа работ', 'Тип работ', 
						'Срок (дней)', 'Окончание', 'Приход', 'Расход', 'Баланс', 'Примечание'];
        var col_model = [
		    { name: 'status', index: 'status', hidden: true, width: 1, fixed: true, 
				sortable: false, search: false, editable: true,
				editoptions: { dataInit: function (el) { el_status = el; } }
			},
		    { name: 'id', index: 'job_id', hidden: false, width: 50, editable: false, 
				formoptions: { label: '<div class="jqg-form-label">Идентификатор</div>'}
			},
			{ name: 'job_start', index:'job_start', hidden: false, width:80, editable: true,
            	editoptions: { style: "width:250px;", dataInit: function (el) { el_start = el; } },
				formoptions: { label: '<div class="jqg-form-label">Дата начала</div>'}
			},         
		    { name: 'job_cost', index: 'job_cost', hidden: false, width: 80, align:'right', 
				sortable: false, search: false, editable: true,
				formatter:'number', formatoptions:{decimalSeparator:'.',decimalPlaces:2,thousandsSeparator:' '},
            	editoptions: { maxlength: "16", style: "width:250px;" },
				formoptions: { label: '<div class="jqg-form-label">Стоимость работ</div>'}
		    },
		    { name: 'build_id', index: 'build_id', hidden: true, width: 1, 
				sortable: false, search: false, editable: true,
		        editoptions: { maxlength: "16", dataInit: function (el) { el_build_id = el; } }
		    },
		    { name: 'build_name', index: 'build_name', hidden: false, width: 100, editable: true,
		        editoptions: { maxlength: "16", style: "width:250px;", dataInit: function (el) { el_build_name = el; } },
				formoptions: { label: '<div class="jqg-form-label">Шифр объекта</div>'}
		    },
		    { name: 'cli_id', index: 'cli_id', hidden: true, width: 1, 
				sortable: false, search: false, editable: true,
		        editoptions: { maxlength: "16", dataInit: function (el) { el_cli_id = el; } }
		    },
		    { name: 'cli_name', index: 'cli_name', hidden: false, width: 200, search: true, editable: true,
		        editoptions: { maxlength: "64", style: "width:250px;", dataInit: function (el) { el_cli_name = el; } },
				formoptions: { label: '<div class="jqg-form-label">Заказчик работ</div>'}
		    },
		    { name: 'jtp_id', index: 'jtp_id', hidden: true, width: 1, 
				sortable: false, search: false, editable: true,
		        editoptions: { maxlength: "16", dataInit: function (el) { el_jtp_id = el; } }
		    },
		    { name: 'jtp_descr', index: 'jtp_descr', hidden: false, width: 200,
				sortable: false, search: true, editable: true,
		        editoptions: { maxlength: "128", style: "width:250px;", dataInit: function (el) { el_jtp_descr = el; } },
				formoptions: { label: '<div class="jqg-form-label">Тип работ</div>'}
		    },
		    { name: 'job_duration', index: 'job_duration', hidden: false, width: 70, align:'right',
				sortable: false, search: false, editable: true,
				formatter:'number', formatoptions:{decimalSeparator:'.',decimalPlaces:0,thousandsSeparator:' '},
		        editoptions: { maxlength: "16", style: "width:250px;" },
				formoptions: { label: '<div class="jqg-form-label">Срок (дней)</div>'}
		    },
			{ name: 'job_finish', index:'job_finish', hidden: false, width:80, editable: true,
            	editoptions: { style: "width:250px;", dataInit: function (el) { el_finish = el; } },
				formoptions: { label: '<div class="jqg-form-label">Дата окончания</div>'}
			},         
		    { name: 'totp_inc', index: 'totp_inc', hidden: false, width: 80, align:'right', 
				sortable: false, search: false, editable: false,
				formatter:'number', formatoptions:{decimalSeparator:'.',decimalPlaces:2,thousandsSeparator:' '}
		    },
		    { name: 'totp_out', index: 'totp_out', hidden: false, width: 80, align:'right', 
				sortable: false, search: false, editable: false,
				formatter:'number', formatoptions:{decimalSeparator:'.',decimalPlaces:2,thousandsSeparator:' '}
		    },
		    { name: 'totp_bal', index: 'totp_bal', hidden: false, width: 80, align:'right', 
				sortable: false, search: false, editable: false,
				formatter:'number', formatoptions:{decimalSeparator:'.',decimalPlaces:2,thousandsSeparator:' '}
		    },
		    { name: 'job_comment', index: 'job_comment', hidden: false, width: 150, 
				sortable: false, search: false, editable: true,
		        editoptions: { style: "width:250px;" },
				formoptions: { label: '<div class="jqg-form-label">Примечание</div>'}
		    }
        ];

        var jqgo = {
            url: 'index.php',
            editurl: 'index.php',
            datatype: 'json',
            postData: { q: 'jobs/index' },
            emptyrecords: true,
            autowidth: false,
            gridview: true,
            hidegrid: false,
            hoverrows: true,
            recordpos: 'right',
            scrollrows: true,
            multiselect: true,
            multiselectWidth: 25,
            multiboxonly: true,
            mtype: 'POST',
            colNames: col_names,
            colModel: col_model,
            page: 1,
            pager: pager,
            pagerpos: 'right',
            rowNum: 50,
            rowList: [50, 200, 1000],
            //		    viewrecords: true,
            loadui: 'disable',
            toolbar: [false, 'top'],
			toppager: false,
            filterbar: false,
            shrinkToFit: false,
            height: $('#'+area_id).innerHeight() - 77,
            width: $('#'+area_id).innerWidth() - 2,
            sortname: 'job_start',
            sortorder: 'desc',
            sortable: true,
            caption: '',
            loadError: function () {
                alert("Ошибка загрузки даных");
            },
            loadComplete: function (data) {
                switch( data.userdata.errcode ) {
                    case 0:
                        break;
                    case 99:
                        app.alert('AlertDlg', 'Ошибка', data.userdata.errmess, 'app-icon-stop32', caller.Close );
                        break;
                    default:
                        app.alert('AlertDlg', 'Ошибка', data.userdata.errmess, 'app-icon-stop32' );
                        break;
                }
				var row_id, status;
				var stats = gritab.getCol( 'status', true );
				for( var i=0; i<stats.length; i++ ) {
					row_id = stats[i].id;
					status = stats[i].value;
					if( (status & 1 ) == 1 ) {
						gritab.jqGrid('setCell',row_id,'id','','ui-state-error');
					}
				}
            },
            ondblClickRow: onEditClick
        };

// Редактирование
        function onEditClick() { 
			var rowarr = gritab.getGridParam('selarrrow');
			if( rowarr.length == 0 ) { selRowPlease(); return; }
			if( rowarr.length > 1 ) { selOnePlease(); return; }
				
            $.post('index.php', { q: 'jobs/jobstate', job_ids: rowarr }, function (rsp, textStatus) {
				if( typeof rsp != 'object' ) rsp = $.parseJSON(rsp);
                if (rsp.errcode) { app.alert('AlertDlg', 'Ошибка', rsp.errmess, 'app-icon-stop32'); return; }
				var jobstate = rsp.data[0].state;
				gritab.jqGrid('editGridRow', rowarr[0], {
					width: 400,
					resize: false,
                    modal: true,
                    jqModal: true,
					zIndex: app.ui_dialog_min_z_index+1,
                    editData: { q: 'jobs/update' },
					onInitializeForm: function( fm ) {
						$(fm).prepend('<style type="text/css">.ui-autocomplete {max-width:262px;}</style>'); 
					},
                    afterShowForm: function(fm) {
						var elms = $(fm).find(".EditTable tr.FormData");
						elms.hide();
						switch( jobstate & 0x6 ) {
							case 0:
								elms.filter("tr#tr_job_start, tr#tr_job_cost, tr#tr_build_name, tr#tr_cli_name, "+
									"tr#tr_jtp_descr, tr#tr_job_duration, tr#tr_job_comment" ).show(); 
								break;
							case 2:
								elms.hide();
								elms.filter("tr#tr_job_cost, tr#tr_job_duration, tr#tr_job_finish, tr#tr_job_comment").show(); 
								break;
							case 6:
								elms.hide();
								elms.filter("tr#tr_job_cost, tr#tr_job_duration, tr#tr_job_finish, tr#tr_job_comment").show(); 
								break;
						}
						onShowEditForm(fm);
					},
                    afterSubmit: responseOnSubmit,
                    viewPagerButtons: false,
                    closeAfterEdit: true,
					onClose: onCloseEditForm
				});
            }, 'json');			
		}
		
		function onShowEditForm(fm) {
            BindCalendar(fm, $(el_start));
            BindCalendar(fm, $(el_finish));
			SetBuildHack();
			SetClientsHack();
			SetJtpHack();
            $(edit_div).css({'overflow':'visible'}).shadow();
		}
		        
		function onCloseEditForm() {
			$(el_build_name).autocomplete( "destroy" ).unbind();
			$(el_cli_name).autocomplete( "destroy" ).unbind();
			$(el_jtp_descr).autocomplete( "destroy" ).unbind();
			$(el_start).datepicker( "destroy" ).unbind();
			$(el_finish).datepicker( "destroy" ).unbind();
			return true;
		}
		
// Создадим jqGrid
        gritab = $('#' + vdiv).jqGrid(jqgo);

// Индикация ошибок при вводе, ред., удал.
        function TestNewData(pd, formid) {
            var result = true, mess = '';
/*			
            if( pd.inc_cont_id == '' || pd.inc_build_id == '' || pd.inc_bank_date == '') {
                result = false;
                mess = 'Данные введены с ошибками !!!';
            }
*/
            return[result,mess];
        }
        
// Индикация серверных ошибок добавления, ред., удал.
        function responseOnSubmit(response, postdata) {
            var rsp = $.parseJSON(response.responseText);
            var success = true;
            var msg = '';

            if (rsp.errcode) {
                success = false;
                msg = rsp.errmess;
            }
				
            return [success, msg];
        }

// Навигатор - создаем панель инструментов
        gritab.jqGrid('navGrid', pager_id, {
				add:false,del:false,edit:false,view:false,search:false,refresh:false });
        
// Пользовательский навигатор - создать
        gritab.jqGrid('navButtonAdd', pager_id, {
            caption: 'Добавить',
            title: 'Создать запись',
            buttonicon: 'ui-icon-plus',
            onClickButton: function() { 
				gritab.jqGrid('editGridRow', 'new', {
					width: 400,
					resize: false,
                    modal: true,
                    jqModal: true,
					zIndex: app.ui_dialog_min_z_index+1,
                    editData: { q: 'jobs/insert' },
					onInitializeForm: function( fm ) {
						$(fm).prepend('<style type="text/css">.ui-autocomplete {max-width:252px;}</style>'); },
                    afterShowForm: function(fm) {
						var elms = $(fm).find(".EditTable tr.FormData");
						elms.hide();
						elms.filter("tr#tr_job_start, tr#tr_job_cost, tr#tr_build_name, tr#tr_cli_name, "+
									"tr#tr_jtp_descr, tr#tr_job_duration, tr#tr_job_comment" ).show(); 
						onShowEditForm(fm);
					},
                    afterSubmit: responseOnSubmit,
					beforeSubmit: TestNewData, 
                    closeAfterAdd: false,
					onClose: onCloseEditForm
				});
			}
        });
// Пользовательский навигатор - редактирование
        gritab.jqGrid('navButtonAdd', pager_id, {
            caption: 'Изменить',
            title: 'Редактировать выбранную запись',
            buttonicon: 'ui-icon-pencil',
            onClickButton: onEditClick
		});
		
// Пользовательский навигатор - удаление
        gritab.jqGrid('navButtonAdd', pager_id, {
            caption: 'Удалить',
            title: 'Удаление выбранной записи',
            buttonicon: 'ui-icon-trash',
            onClickButton: function() {
				var rowarr = gritab.getGridParam('selarrrow');
				var rowlist = rowarr.toString();
				if( rowarr.length == 0 ) { selRowPlease(); return; }
				
				$.post('index.php', { q: 'jobs/jobstate', job_ids: rowarr }, function (rsp, textStatus) {
					var rowdis = '';
					if( typeof rsp != 'object' ) rsp = $.parseJSON(rsp);

					if (rsp.errcode) { app.alert('AlertDlg', 'Ошибка', rsp.errmess, 'app-icon-stop32'); return; }
					var jobstate = rsp.data;

					for( var i = 0; i < jobstate.length; i++ ) {
						if( jobstate[i].state & 0x6 )
							rowdis += (rowdis.length ? ', ' : '' )+"'"+jobstate[i].id+"'";
					}
					if( rowdis.length ) {
						app.alert('AlertDlg', 'Внимание', "Удаление позиции(й) "+rowdis+" уже запрещено.", 'app-icon-stop32');
						return;
					}
					gritab.jqGrid('delGridRow', rowlist, {
						modal: true,
						jqModal: true,
						width: 250,
						msg: '<table style="width:240px;margin-top:16px;"><tr><td style="width:50px;">'+
								'<div class="app-icon-quest32"></div></td><td>Удалить выбранную запись(и) ?</td></tr></table>',
						resize: false,
						zIndex: app.ui_dialog_min_z_index+1,
						closeOnEscape: true,
						delData: { q: 'jobs/delete' },
						afterShowForm: function() { $('div#delmod' + vdiv).shadow(); },
						afterSubmit: responseOnSubmit
					});
				});
			}
        });
		
// Пользовательский навигатор - просмотр
        gritab.jqGrid('navButtonAdd', pager_id, {
            caption: 'Просмотр',
            title: 'Показать в виде формы',
            buttonicon: 'ui-icon-document',
            onClickButton: function() { 
				var rowlist = gritab.getGridParam('selarrrow');
				if( rowlist.length == 0 ) { selRowPlease(); return; }
				if( rowlist.length > 1 ) {
					app.alert('AlertDlg', 'Внимание', "Пожалуйста, выберите только одну строку в таблице.", 'app-icon-stop32');
					return;
				}
				gritab.jqGrid('viewGridRow', rowlist[0], {
					width: 400,
					resize: true,
                    modal: true,
                    jqModal: true,
					zIndex: app.ui_dialog_min_z_index+1,
                    closeOnEscape: true,
                    viewPagerButtons: false,
					labelswidth: '30%',
					beforeShowForm: function(fm) { 
						$(fm).find("table:first td").css({'white-space':'normal','vertical-align':'top'});
						$('div#viewmod' + vdiv).shadow(); 
					}
				});
			}
        });
		
// Пользовательский навигатор - обновить
		gritab.jqGrid('navButtonAdd',pager_id,{
			caption: 'Обновить',
			title: 'Обновить таблицу',
			buttonicon: 'ui-icon-refresh',
			onClickButton: function() { 	gritab.trigger("reloadGrid"); }
		});    
        
// Пользовательский навигатор - баланс
		gritab.jqGrid('navButtonAdd',pager_id,{
			caption: 'Баланс',
			title: 'Показать баланс',
			buttonicon: 'ui-icon-shuffle',
			onClickButton: function() { 
				var rowarr = gritab.getGridParam('selarrrow');
				var rowlist = rowarr.toString();
				if( rowarr.length == 0 ) { selRowPlease(); return; }
				
				var fpost = area_id+'_BalanceForm';
				area.append(
				'<form id="'+fpost+'" style="display:none" target="balance" method="post" '+
					'action="index.php?q=jobs/selbal"><input name="job_ids" value="'+rowlist+'"></form>'
				);
				window.open(null, 'balance', 'location=0,status=0,toolbar=0,menubar,resizable,scrollbars,height=600,width=1000');
				$('#'+fpost).submit();
				$('#'+fpost).remove();
			}

		});    
        
// Делаем ширину панели кнопок максимальной
		$('td#'+area_id+'TabPager_center').width(2);
		
        gritab.filterToolbar({ searchOnEnter: false, afterSearch: function () { } });

// Прикрепить календарь к ячейке поиска
		BindCalendar( $("#gview_"+vdiv+" tr.ui-search-toolbar"), $("#gview_" + vdiv + " #gs_job_start") );
		BindCalendar( $("#gview_"+vdiv+" tr.ui-search-toolbar"), $("#gview_" + vdiv + " #gs_job_finish") );
		
        function BindCalendar(fm, el) {
			var tb = $(fm).hasClass('ui-search-toolbar');
            $(el).datepicker({
				onClose: function(dt, inst) {				
					if( tb && dt != '' ) gritab[0].triggerToolbar();
				},
                dateFormat: "dd.mm.yy",
                showOn: "button",
                buttonImage: "img/calendar2.png",
                buttonImageOnly: true,
                buttonText: "Календарь",
                changeMonth: tb,
                changeYear: tb
            });

            fm.find(".ui-datepicker-trigger")
                .css({ 'cursor': 'pointer', 'position': 'relative', 'left': '-18px', 'top': '3px' });
            $(el).attr("title", "Формат ввода: 'дд.мм.гггг'");                
        }

		
        function SetBuildHack() {
            $(el_build_name).autocomplete({
				html: true,
				appendTo: 'div#editmod' + vdiv,
                source: function (request, responce) {
                    $.post('index.php', { q: 'builds/find', term: request.term },
                    function (rsp, textStatus) {
						if( typeof rsp != 'object' ) rsp = $.parseJSON(rsp);
                        if (rsp.errcode) {
                            if (rsp.errcode == '999') { alert(rsp.errmess); }
                            else app.alert('AlertDlg', 'Ошибка', rsp.errmess, 'app-icon-stop32');
                            responce();
                            return;
                        }
                        if (rsp.data) {
                            responce($.map(rsp.data, function (item) {
                                return { label: item.name + ' ( '+item.address+' )', 
										value:item.value, name:item.name, address:item.address }
                            }));
                            return;
                        }
                        responce();
                    }, 
                    'json');
                },
                minLength: 2, autoFocus: true,
                focus: function (event, ui) { return false; },
                select: function (event, ui) {
                    $(el_build_id).val(ui.item.value);
                    build_name = ui.item.name.replace(/<(b|\/b)>/g,'');
                    $(el_build_name).val(build_name);
                    return false;
                }
            });
			build_name = $(el_build_name).val();
            $(el_build_name).bind( 'focusout', function () { 
                if( $(el_build_name).val() != build_name ) { 
                    build_name = '';
                    $(el_build_name).val('');
                    $(el_build_id).val("");
                }
            });            
        }

        function SetClientsHack() {
            $(el_cli_name).autocomplete({
				html: true,
				appendTo: 'div#editmod' + vdiv,
                source: function (request, responce) {
                    $.post('index.php', { q: 'clients/find', term: request.term },
                    function (rsp, textStatus) {
						if( typeof rsp != 'object' ) rsp = $.parseJSON(rsp);
                        if (rsp.errcode) {
                            if (rsp.errcode == '999') { alert(rsp.errmess); }
                            else app.alert('AlertDlg', 'Ошибка', rsp.errmess, 'app-icon-stop32');
                            responce();
                            return;
                        }
                        if (rsp.data) {
                            responce($.map(rsp.data, function (item) {
                                return { label: item.name, value: item.value }
                            }));
                            return;
                        }
                        responce();
                    }, 
                    'json');
                },
                minLength: 2, autoFocus: true,
                focus: function (event, ui) { return false; },
                select: function (event, ui) {
					$(el_cli_id).val(ui.item.value);
                    cli_name = ui.item.label.replace(/<(b|\/b)>/g,'');
                    $(el_cli_name).val(cli_name);
					return false;
                }
            });
			
			$cli_name = $(el_cli_name).val();
            $(el_cli_name).bind( 'focusout', function () {
                if( $(el_cli_name).val() != cli_name ) {
                    $(el_cli_id).val('')
                    $(el_cli_name).val('')
                    vend_name = '';
                }
			});
        }

        function SetJtpHack() {
            $(el_jtp_descr).autocomplete({
				html: true,
				appendTo: 'div#editmod' + vdiv,
                source: function (request, responce) {
                    $.post('index.php', { q: 'payments/findjtp', term: request.term },
                    function (rsp, textStatus) {
						if( typeof rsp != 'object' ) rsp = $.parseJSON(rsp);
                        if (rsp.errcode) {
                            if (rsp.errcode == '999') { alert(rsp.errmess); }
                            else app.alert('AlertDlg', 'Ошибка', rsp.errmess, 'app-icon-stop32');
                            responce();
                            return;
                        }
                        if (rsp.data) {
                            responce($.map(rsp.data, function (item) {
                                return { label: item.jtp_descr, value: item.jtp_id }
                            }));
                            return;
                        }
                        responce();
                    }, 
                    'json');
                },
                minLength: 2, autoFocus: true,
                focus: function (event, ui) { return false; },
                select: function (event, ui) {
					$(el_jtp_id).val(ui.item.value);
                    jtp_descr = ui.item.label.replace(/<(b|\/b)>/g,'');
                    $(el_jtp_descr).val(jtp_descr);
					return false;
                }
            });
			
			$jtp_descr = $(el_jtp_descr).val();
            $(el_jtp_descr).bind( 'focusout', function () {
                if( $(el_jtp_descr).val() != jtp_descr ) {
                    $(el_jtp_id).val('')
                    $(el_jtp_descr).val('')
                    jtp_descr = '';
                }
			});
        }

		this.Destroy = function() {
			$("#gview_" + vdiv + " #gs_job_start").datepicker( "destroy" ).unbind();
			$("#gview_" + vdiv + " #gs_job_finish").datepicker( "destroy" ).unbind();
			gritab.GridDestroy(vdiv);
			area.empty();
		};
		this.Resize = function() {
			gritab.setGridWidth( area.innerWidth() - 2 );
			gritab.setGridHeight( area.innerHeight() - 77 );
		};

	};  // End of create function definition


	function JobsProxy() {
		var oTab, area;
		var active = false;
		
		this.Open = function( area_id ) {
			if( active  ) return;
			area = area_id;
			$('#'+area+'Title').show();
			oTab = new Jobs( area_id, this ); 
			$(window).bind( 'resize', oTab.Resize );
			active = true;
		};
		this.Close = function() { 
			if( !active  ) return;
			$(window).unbind( 'resize', oTab.Resize );
			oTab.Destroy();
			$('#'+area+'Title').hide();
			active = false;
		};
		this.Resize = function() { oTab.Resize(); };
	}
	
	app.Jobs = new JobsProxy();
	
    // ---------------------------------------------------------------------------
})(jQuery);
